import React, { useEffect, useState } from 'react';
import { Toast as BootstrapToast } from 'react-bootstrap';
import { useTranslation } from 'react-i18next';


export interface ToastProps {
    type: 'success' | 'danger' | 'info' | 'warning';
    message: string;
    onClose?: () => void;
    autoClose?: boolean;
    autoCloseTime?: number;
}

/**
 * Toast component for showing notifications
 */
const Toast: React.FC<ToastProps> = ({
    type = 'info',
    message,
    onClose,
    autoClose = true,
    autoCloseTime = 5000
}) => {
    const [show, setShow] = useState(true);
    const { t } = useTranslation();

    // Handle auto-close behavior
    useEffect(() => {
        if (autoClose) {
            const timer = setTimeout(() => {
                setShow(false);
                if (onClose) onClose();
            }, autoCloseTime);

            return () => clearTimeout(timer);
        }
    }, [autoClose, autoCloseTime, onClose]);

    const handleClose = () => {
        setShow(false);
        if (onClose) onClose();
    };

    // Get icon based on type
    const getIcon = () => {
        switch (type) {
            case 'danger':
                return 'bi-exclamation-circle';
            case 'info':
                return 'bi-info-circle';
            case 'warning':
                return 'bi-exclamation-triangle';
            case 'success':
                return 'bi-check-circle';
            default:
                return 'bi-info-circle';
        }
    };

    // Try to translate the message, fallback to original if translation fails
    const translatedMessage = (() => {
        try {
            return t(message);
        } catch {
            return message;
        }
    })();

    return (
        <BootstrapToast
            show={show}
            onClose={handleClose}
            className={`bg-${type} text-white`}
            delay={autoCloseTime}
            autohide={autoClose}
            style={{
                position: 'fixed',
                bottom: '1rem',
                right: '1rem',
                zIndex: 1060,
                minWidth: '250px'
            }}
        >
            <BootstrapToast.Header className={`bg-${type} text-white border-0`}>
                <i className={`bi ${getIcon()} me-2`}></i>
                <strong className="me-auto">
                    {type === 'danger' ? 'Error' : type.charAt(0).toUpperCase() + type.slice(1)}
                </strong>
                <small className="text-white">just now</small>
            </BootstrapToast.Header>
            <BootstrapToast.Body>{translatedMessage}</BootstrapToast.Body>
        </BootstrapToast>
    );
};

export default Toast; 